<template>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/welcome">系统管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
  </el-card>
  <el-card class="box-card">
    <el-row class="mb-4">
      <el-button type="primary" @click="openAddForm">添加用户</el-button>
    </el-row>
    <el-form
      :inline="true"
      ref="userFormRef"
      :model="userForm"
      class="form-inline"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="用户名">
            <el-input
              v-model="userForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="昵称">
            <el-input
              v-model="userForm.nickname"
              placeholder="请输入昵称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮箱">
            <el-input
              v-model="userForm.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电话">
            <el-input
              v-model="userForm.phoneNumber"
              placeholder="请输入电话"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="状 态">
            <el-select
              v-model="userForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="禁用" value="0" />
              <el-option label="启用" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性 别">
            <el-select
              v-model="userForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option label="男" value="0" />
              <el-option label="女" value="1" />
              <el-option label="保密" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="danger" @click="resetForm(userFormRef)"
              >重置</el-button
            >
            <el-button type="primary" @click="exportExcel">导出</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6"> </el-col>
      </el-row>
    </el-form>
    <el-table
      :data="tableData"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      border
      style="width: 100%"
    >
      <el-table-column fixed prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="nickname" label="昵称" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="avatar" label="头像" width="150">
        <template #default="scope">
          <!-- {{ scope.row.avatar }} -->
          <el-avatar shape="square" :size="100" :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="联系电话" width="120" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <!-- <el-tag
            class="ml-2"
            size="small"
            type="success"
            v-if="scope.row.status == 1"
            >启用</el-tag
          >
          <el-tag
            class="ml-2"
            size="small"
            type="danger"
            v-if="scope.row.status == 0"
            >禁用</el-tag
          > -->
          <el-switch
            v-model="scope.row.status"
            class="ml-2"
            inline-prompt
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          <el-tag
            class="ml-2"
            size="small"
            type="success"
            v-if="scope.row.sex == 0"
            >男</el-tag
          >
          <el-tag
            class="ml-2"
            size="small"
            type="danger"
            v-if="scope.row.sex == 1"
            >女</el-tag
          >
          <el-tag
            class="ml-2"
            size="small"
            type="info"
            v-if="scope.row.sex == 2"
            >保密</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        sortable
        label="创建时间"
        width="180"
      />
      <el-table-column prop="birth" label="生日" width="180" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="removeUser(scope.row)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="editUser(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[2, 3, 4, 5]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogVisible"
      title="添加新用户"
      width="900px"
      :before-close="handleClose"
      destroy-on-close
    >
      <!-- 新增用户表单 -->
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserRules"
        label-width="120px"
        class="add-user-form"
      >
        <!-- 第一行：用户名 + 昵称 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="addUserForm.username"
                placeholder="请输入用户名（2-20字符）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="addUserForm.nickname"
                placeholder="请输入用户昵称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：密码 + 确认密码（可选，根据需求决定是否添加） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="addUserForm.password"
                type="password"
                placeholder="请输入密码（6-32字符）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="addUserForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：邮箱 + 电话 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="addUserForm.email"
                placeholder="请输入用户邮箱（如xxx@xxx.com）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input
                v-model="addUserForm.phoneNumber"
                placeholder="请输入11位手机号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：状态 + 性别 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="addUserForm.status" placeholder="请选择状态">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="addUserForm.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="保密" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：生日 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="生日" prop="birth">
              <el-date-picker
                v-model="addUserForm.birth"
                type="date"
                placeholder="请选择用户生日"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：头像上传 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户头像">
              <el-upload
                list-type="picture-card"
                :auto-upload="true"
                :before-upload="beforeAvatarUpload"
                :limit="1"
                :multiple="false"
                action="http://localhost:8088/oss/uploadFile"
                @success="uploadSuccess"
                @remove="removeFile"
              >
                <img
                  style="width: 146px; height: 146px"
                  v-if="addUserForm.avatar"
                  :src="addUserForm.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div
                style="
                  margin-top: 10px;
                  margin-left: 10px;
                  size: 12px;
                  color: #666;
                "
              >
                提示：支持JPG、PNG格式，建议尺寸200x200px，大小不超过2M
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹窗底部按钮区 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose((done) => done())">取消</el-button>
          <el-button type="primary" @click="submitAddUser">提交添加</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import {
  list,
  addUser,
  updateUser,
  deleteUser,
  modifyStatus,
  deleteFile,
  exportUserExcel
} from "@/api/user";
import { reactive } from "vue";
const pageNum = ref(1);
const pageSize = ref(2);
const total = ref(0);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
//是否弹框
const dialogVisible = ref(false);

const userForm = reactive({
  pageNum: 1,
  pageSize: 2,
  username: "",
  nickname: "",
  email: "",
  phoneNumber: "",
  status: "",
  sex: "",
});

// 1. 新增：添加用户表单的响应式数据（与弹窗表单绑定）
const addUserForm = reactive({
  username: "", // 用户名（必填）
  nickname: "", // 昵称
  password: "", // 密码（必填）
  email: "", // 邮箱
  phoneNumber: "", // 电话
  status: 1, // 状态（默认启用：1）
  sex: 2, // 性别（默认保密：2）
  birth: "", // 生日
  avatar: "", // 头像URL
});

// 2. 新增：表单验证规则（与Element Plus表单验证配合）
const addUserRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "用户名长度需在2-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 32, message: "密码长度需在6-32个字符之间", trigger: "blur" },
  ],
  email: [
    {
      pattern: /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]+$/,
      message: "请输入合法邮箱",
      trigger: "blur",
    },
  ],
  phoneNumber: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入合法手机号", trigger: "blur" },
  ],
});

// 3. 新增：表单引用（用于表单验证、重置）
const addUserFormRef = ref(null);

// 当使用Vue3中的setUp语法的时候,一定要使用ref去定义变量,reactive()定义属性的
const tableData = ref([]);

onMounted(() => {
  getUserList();
});

const getUserList = async () => {
  var userQueryVO = {
    ...userForm,
  };

  const result = await list(userQueryVO);
  console.log(result);
  if (result.code === 200 && result.success) {
    ElNotification({
      title: "Success",
      message: "用户数据查询成功！",
      type: "success",
    });
    tableData.value = result.data.userPage.records;
    total.value = result.data.userPage.total;
  } else {
    console.log("失败");
  }
};

const removeUser = async (row) => {
  try {
    // 调用添加用户接口（传入表单数据）
    const result = await deleteUser(row.id);
    console.log(result);
    if (result.code === 200 && result.success) {
      ElNotification({
        title: "成功",
        message: "用户删除成功！",
        type: "success",
      });
      getUserList(); // 重新获取用户列表，展示新增数据
    } else {
      ElMessage.error("用户删除失败：" + (result.message || "未知错误"));
    }
  } catch (err) {
    ElMessage.error("接口请求失败，请检查网络或后端服务");
    console.error("删除用户错误：", err);
  }
};

const editUser = (row) => {
  resetAddUserForm();
  console.log(addUserForm);
  for (const key in row) {
    addUserForm[key] = row[key];
  }
  dialogVisible.value = true;
};

const changeStatus = async (row) => {
  console.log(row)
  let zt = row.status;
  try {
    // 调用添加用户接口（传入表单数据）
    const result = await modifyStatus(row.id, zt);
    console.log(result);
    if (result.code === 200 && result.success) {
      ElNotification({
        title: "成功",
        message: "状态修改成功！",
        type: "success",
      });
      getUserList(); // 重新获取用户列表，展示新增数据
    } else {
      ElMessage.error("状态修改失败" + (result.message || "未知错误"));
    }
  } catch (err) {
    ElMessage.error("接口请求失败，请检查网络或后端服务");
    console.error("状态修改错误：", err);
  }
};

const openAddForm = () => {
  resetAddUserForm();
  for (const key in addUserForm) {
    addUserForm[key] = "";
  }
  dialogVisible.value = true;
};

const onSubmit = () => {
  getUserList();
};

/**
 * 导出用户列表Excel
 */
const exportExcel = async () => {
  // 1. 处理筛选参数：移除分页参数（pageNum/pageSize），保留筛选条件
  const exportParams = { ...userForm };
  delete exportParams.pageNum; // 删除分页页码
  delete exportParams.pageSize; // 删除分页大小

  // 2. 处理参数类型（可选，根据后台要求调整）
  // 例：前端status是字符串（el-select绑定value），后台需数字类型
  if (exportParams.status !== "")
    exportParams.status = Number(exportParams.status);
  if (exportParams.sex !== "") exportParams.sex = Number(exportParams.sex);

  // 3. 显示加载提示（数据量大时提升体验）
  const loading = ElLoading.service({
    lock: true,
    text: "正在导出数据，请稍候...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    const response = await exportUserExcel(exportParams);

    // --------------- 修复：解析文件名逻辑（增加异常判断） ---------------
    let fileName = "用户列表.xlsx"; // 默认文件名
    const contentDisposition = response.headers["content-disposition"]; // 注意：header 可能是小写（axios 会标准化）

    // 只有当 contentDisposition 存在且包含 'filename=' 时，才解析文件名
    if (contentDisposition && contentDisposition.includes("filename=")) {
      // 处理两种格式：filename=xxx 或 filename*=UTF-8''xxx
      const filenamePart = contentDisposition.split("filename=")[1];
      if (filenamePart) {
        // 移除可能的引号（如 "用户列表.xlsx" → 用户列表.xlsx）
        fileName = decodeURIComponent(filenamePart.replace(/"/g, ""));
        // 处理 filename*=UTF-8''xxx 的情况（split 后可能包含 UTF-8'' 前缀）
        if (fileName.startsWith("UTF-8''")) {
          fileName = fileName.slice(6); // 去掉前缀 "UTF-8''"
        }
      }
    }
    // -------------------------------------------------------------------

    // 后续处理 blob 和下载逻辑不变...
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success(`数据导出成功！文件名：${fileName}`);
  } catch (error) {
    // 10. 错误处理（兼容后台返回blob类型的错误信息）
    let errorMsg = "数据导出失败，请稍后重试";
    if (error.response && error.response.data instanceof Blob) {
      // 若错误响应是blob，转成文本再解析JSON（后台可能返回JSON格式错误）
      const errorText = await new Response(error.response.data).text();
      try {
        const errorJson = JSON.parse(errorText);
        errorMsg = errorJson.message || errorMsg;
      } catch (e) {
        // 非JSON格式错误，直接显示文本
        errorMsg = errorText || errorMsg;
      }
    } else if (error.message) {
      // 网络错误等
      errorMsg = error.message;
    }

    ElMessage.error(errorMsg);
    console.error("Excel导出错误：", error);
  } finally {
    // 11. 关闭加载提示（无论成功/失败）
    loading.close();
  }
};

const resetForm = () => {
  userForm.username = "";
  userForm.nickname = "";
  userForm.email = "";
  userForm.phoneNumber = "";
  userForm.status = "";
  userForm.sex = "";

  getUserList();
};

const handleSizeChange = (val) => {
  userForm.pageSize = val;
  getUserList();
};
const handleCurrentChange = (val) => {
  userForm.pageNum = val;
  getUserList();
};

const handleClose = (done) => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      done();
    })
    .catch(() => {});
};

const removeFile = async (uploadFile, uploadFiles) => {
  if (addUserForm.avatar) {
    await deleteFile(addUserForm.avatar.split("http://hnzbxy.com/")[1]);
  }
};

// 4.上传头像
const uploadSuccess = (response, uploadFile, uploadFiles) => {
  console.log(response);
  if (response.code === 200 && response.success === true) {
    ElMessage({
      message: "头像上传成功",
      type: "success",
    });
    addUserForm.avatar = response.data.url;
  }
};

// 5. 新增：提交添加用户表单
const submitAddUser = async () => {
  if (addUserForm.id) {
    // 先执行表单验证
    addUserFormRef.value.validate(async (isValid) => {
      if (!isValid) return; // 验证失败则终止

      try {
        // 调用添加用户接口（传入表单数据）
        const result = await updateUser(addUserForm);
        console.log(result);
        if (result.code === 200 && result.success) {
          ElNotification({
            title: "成功",
            message: "用户修改成功！",
            type: "success",
          });
          // 关闭弹窗 + 重置表单 + 刷新用户列表
          dialogVisible.value = false;
          resetAddUserForm();
          getUserList(); // 重新获取用户列表，展示新增数据
        } else {
          ElMessage.error("用户修改失败：" + (result.message || "未知错误"));
        }
      } catch (err) {
        ElMessage.error("接口请求失败，请检查网络或后端服务");
        console.error("修改用户错误：", err);
      }
    });
  } else {
    // 先执行表单验证
    addUserFormRef.value.validate(async (isValid) => {
      if (!isValid) return; // 验证失败则终止

      try {
        // 调用添加用户接口（传入表单数据）
        const result = await addUser(addUserForm);
        console.log(result);
        if (result.code === 200 && result.success) {
          ElNotification({
            title: "成功",
            message: "用户添加成功！",
            type: "success",
          });
          // 关闭弹窗 + 重置表单 + 刷新用户列表
          dialogVisible.value = false;
          resetAddUserForm();
          getUserList(); // 重新获取用户列表，展示新增数据
        } else {
          ElMessage.error("用户添加失败：" + (result.message || "未知错误"));
        }
      } catch (err) {
        ElMessage.error("接口请求失败，请检查网络或后端服务");
        console.error("添加用户错误：", err);
      }
    });
  }
};

// 6. 新增：重置添加用户表单
const resetAddUserForm = () => {
  if (addUserFormRef.value) {
    addUserFormRef.value.resetFields(); // 重置表单（清空值 + 清除验证状态）
  }
  addUserForm.avatar = ""; // 清空头像URL
};

// 上传头像之前的校验
const beforeAvatarUpload = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/webp"
  ) {
    ElMessage.error("头像的图片必须是jpg类型");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("头像图片的大小不能超过2M!");
    return false;
  }
  return true;
};
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  margin-top: 10px;
}

.form-inline .el-input {
  --el-input-width: 220px;
}

.form-inline .el-select {
  --el-select-width: 220px;
}

.el-pagination {
  margin-top: 10px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 所有表格内容居中 */
::v-deep .el-table td,
::v-deep .el-table th {
  text-align: center !important;
}

.el-pagination {
  margin-top: 10px;
  text-align: right;
}

.el-form {
  margin-top: 10px;
  text-align: right;
}
</style>
